// @system GO-CRAWL <shop-yun.com>
// @version go-crawl 1.0
// @author xiaotangren  <unphp@qq.com>
// @data 2014-07-29

package main

import (
	"bufio"
	"fmt"
	"os"
	conf "shop-yun.go/go-crawl/utils/conf"
	socket "shop-yun.go/go-crawl/utils/socket"
	"strconv"
	"time"
)

func main() {
	host := conf.CoreConf.Get("common", "sockethost").String()
	protocol := conf.CoreConf.Get("common", "socketprotocol").String()
	socketport := conf.CoreConf.Get("common", "socketport").String()
	//stoptag := conf.CoreConf.Get("common", "socketstoptag").String()
	//启动系统服务
	go socket.NewSockey(protocol, host, socketport, conf.CoreLog).Run()
	//启动系统日志
	listen(conf.CoreConf.Get("common", "logpath").String(), conf.CoreLog)
	defer func() {
		conf.CoreDbpool.Close()
	}()
}

//监听服务运行状态，记录服务日志。
func listen(logpath string, Log *conf.Log) {
	os.MkdirAll(logpath+"/syslog", 0755)
	syslogfiles, _ := os.OpenFile(logpath+"/syslog/syslog_"+strconv.Itoa(int(time.Now().Unix())), os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
	defer func() {
		syslogfiles.Close()
	}()
	syslogwriter := bufio.NewWriter(syslogfiles)
	syslogwriter.WriteString("-------------------服务开始启动--------------------" + "\r\n")
	syslogwriter.WriteString("Date:" + strconv.Itoa(int(time.Now().Unix())) + "\r\n")
	defer func() {
		if err := recover(); err != nil {
			syslogwriter.WriteString("main run return err")
		}
		syslogfiles.Close()
	}()
	for {
		select {
		case msg := <-Log.ChanLogMsg:
			for _, v := range msg {
				fmt.Println(v)
				syslogwriter.WriteString(v + "\r\n")
			}
			syslogwriter.Flush()
		default:
		}
		time.Sleep(1 * time.Second)
	}
}
